<?php

class Silk_View_Helper_HasPermission {

    public function hasPermission($pPermission, $pUser=null){

	$session = Silk::getSession();
	$acl     = Silk::getAcl();

	$Permissions = new Silk_Permissions();

	if (is_array($pPermission)){
	    $resource  = $pPermission['resource'];
	    $privilege = $pPermission['privilege'];
	} else if ($pPermission instanceof Silk_Permission){
	    $resource  = $pPermission->resource;
	    $privilege = $pPermission->privilege;
	} else {
	    $permission = $Permissions->fetchByName($pPermission, true);
	    if ($permission){
		$resource  = $permission->resource;
		$privilege = $permission->privilege;
	    } else {
		$permissions = array();
		include(BASE_DIR . 'config/permissions.php');
		if (array_key_exists($pPermission, $permissions)){
		    $resource = $permissions[$pPermission]['resource'];
		    $privilege = $permissions[$pPermission]['privilege'];
		} else
		    return false;
	    }
	}

	logdebug("Silk_View_Helper_HasPermission.hasPermission: resource={$resource} privilege={$privilege}");

	try {
	    if ($session->guest){
		return $acl->isAllowed('role-guest', $resource, $privilege);
	    } else {
		$user = ($pUser) ? $pUser : Silk::getIdentity();
		return $acl->isAllowed($user, $resource, $privilege);
	    }
	} catch (Zend_Acl_Exception $x){
	    //This happened because resource does not exist yet.
	    //TODO: Get default permissions for type
	    return false;
	}
    }
}

?>